<template>
  <div class="demo-collapse">
    <el-collapse v-model="activeNames" @change="handleChange" accordion>

      <el-collapse-item title="商品数据" name="1" :class="{ 'active-item': isActive('1') }">
        <el-form :model="advancedForm" label-width="110px" class="search-form">
       


          <el-form-item label="HS商品代码">
            <el-popover
              v-model:visible="showHsTree"
              trigger="manual"
              placement="right-start"
              :width="700"
              :height="400"
              
            >
              <div class="hs-popover-content" style="width: 680px; ">
                <Hstree
                  :raw-hs="hsData.hs"
                  v-model="advancedForm.hsCode"
                />
              </div>
              <template #reference>
                <el-switch
                  v-model="showHsTree"
                  active-text="选择HS编码"
                 
                  size="small"
                />
              </template>
            </el-popover>
           
          </el-form-item>

          <el-form-item label="报告国">
            <el-select
              v-model="advancedForm.partner"
              placeholder="请选择国家/地区"
              clearable
            >
              <el-option
                v-for="item in ReportCountryTypeOptions"
                :key="item.code"
                :label="item.label"
                :value="item.code"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="伙伴国">
            <el-select
              v-model="advancedForm.address"
              placeholder="请选择国家/地区"
              clearable
            >
              <el-option
                v-for="item in PartnerCountriesTypeOptions"
                :key="item.code"
                :label="item.label"
                :value="item.code"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="其他数值">
            <el-checkbox-group v-model="advancedForm.others">
              <el-checkbox
                v-for="item in checkList"
                :key="item.code"
                :label="item.label"
              />
            </el-checkbox-group>
          </el-form-item>

          <el-form-item class="form-actions">
            <el-button @click="onAdvancedReset">取消</el-button>
            <el-button type="primary" @click="onAdvancedConfirm"
              >搜索</el-button
            >
          </el-form-item>
        </el-form>
      </el-collapse-item>
    
      <el-collapse-item title="服务贸易" name="2" :class="{ 'active-item': isActive('2') }">
        <el-form :model="form" label-width="110px" class="search-form">
        

          <el-form-item label="时间">
            <div class="date-type-group">
              <el-radio-group v-model="form.dateType" size="small">
                <el-radio label="year">按年</el-radio>
                <el-radio label="month">按月</el-radio>
              </el-radio-group>
            </div>
            <div class="date-pickers">
              <el-date-picker
                v-for="(field, idx) in formDateFields"
                :key="field"
                v-model="form[field]"
                :type="form.dateType"
                :placeholder="pickerPlaceholders[idx]"
                :disabled-date="disabledDate"
              />
            </div>
          </el-form-item>

          <el-form-item label="进出口类型">
            <el-select v-model="form.type" placeholder="请选择">
              <el-option
                v-for="item in tradeTypeOptions"
                :key="item.code"
                :label="item.label"
                :value="item.code"
              />
            </el-select>
          </el-form-item>

         

          <el-form-item class="form-actions">
            <el-button @click="onReset">取消</el-button>
            <el-button type="primary" @click="onSearch">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-collapse-item>

    
     
    </el-collapse>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { QueryDataApi } from '../../api/Data';
import { toYearDate, toMonthDate, formatYear, formatYearMonth } from '../../utils/dateUtils';
import Hstree from './GlHstree.vue'
import { hsData } from '../../utils/GlobalhsData.js';
const isActive = name => activeNames.value === name;
const emit = defineEmits(['macro-search'])
const activeNames = ref('1');
const form = ref({ report: '', dateType: 'year', yearStart: null, yearEnd: null, yearMonthStart: null, yearMonthEnd: null, type: '', statisticsType: [] });
const advancedForm = ref({ tradeType: '', dateMode: 'year', yearStart: null, yearEnd: null, yearMonthStart: null, yearMonthEnd: null, hsCode: '', partner: '', address: '', others: [] });


// 下拉选项

const tradeTypeOptions = ref([]);
const ReportCountryTypeOptions = ref([]);
const PartnerCountriesTypeOptions = ref([]);
const checkList = ref([])
const showHsTree = ref(false);


// 时间区间控制
let minYear, maxYear, minYearMonth, maxYearMonth;
const disabledDate = date => {
  const y = date.getFullYear();
  if (form.value.dateType === 'year') return y < minYear || y > maxYear;
  const code = y * 100 + date.getMonth() + 1;
  return code < minYearMonth || code > maxYearMonth;
};

// 动态生成日期字段和占位文本
const formDateFields = computed(() => form.value.dateType === 'year' ? ['yearStart', 'yearEnd'] : ['yearMonthStart', 'yearMonthEnd']);
const pickerPlaceholders = computed(() => form.value.dateType === 'year'
  ? ['开始年份', '结束年份']
  : ['开始月份', '结束月份']
);


const handleChange = val => console.log('激活面板：', val);

// 宏观统计
const onSearch = () => {
  const payload = { report: form.value.report, type: form.value.type, statisticsType: form.value.statisticsType };
  if (form.value.dateType === 'year') {
    payload.yearStart = formatYear(form.value.yearStart);
    payload.yearEnd = formatYear(form.value.yearEnd);
  } else {
    payload.yearMonthStart = formatYearMonth(form.value.yearMonthStart);
    payload.yearMonthEnd = formatYearMonth(form.value.yearMonthEnd);
  }
  console.log('提交宏观统计：', payload);
  QueryDataApi.ChMacroSearch(payload).then(res=>{
    emit('macro-search', res.data)
  })
};

const onReset = () => {
  form.value = { report: '', dateType: 'year', yearStart: null, yearEnd: null, yearMonthStart: null, yearMonthEnd: null, type: '', statisticsType: [] };
};

// 详细统计
const onAdvancedConfirm = () => {
  const payload = { tradeType: advancedForm.value.tradeType, hsCode: advancedForm.value.hsCode, partner: advancedForm.value.partner, address: advancedForm.value.address, others: advancedForm.value.others };
  if (advancedForm.value.dateMode === 'year') {
    payload.yearStart = formatYear(advancedForm.value.yearStart);
    payload.yearEnd = formatYear(advancedForm.value.yearEnd);
  } else {
    payload.yearMonthStart = formatYearMonth(advancedForm.value.yearMonthStart);
    payload.yearMonthEnd = formatYearMonth(advancedForm.value.yearMonthEnd);
  }
  console.log('提交详细统计：', payload);
  // QueryDataApi.searchDetail(payload)
};

const onAdvancedReset = () => {
  advancedForm.value = { tradeType: '', dateMode: 'year', yearStart: null, yearEnd: null, yearMonthStart: null, yearMonthEnd: null, hsCode: '', partner: '', address: '', others: [] };
};

// 初始化数据
onMounted(() => {
  
  QueryDataApi.getDate().then(res => {
    const d = res.data.timeRangeChina;
    minYear = d.yearStart;
    maxYear = d.yearEnd;
    minYearMonth = d.yearMonthStart;
    maxYearMonth = d.yearMonthEnd;
    form.value.yearStart = toYearDate(d.yearStart);
    form.value.yearEnd = toYearDate(d.yearEnd);
    form.value.yearMonthStart = toMonthDate(d.yearMonthStart);
    form.value.yearMonthEnd = toMonthDate(d.yearMonthEnd);
  });
  QueryDataApi.getTradeType().then(res => { tradeTypeOptions.value = Object.values(res.data.exIm || {}); });


  QueryDataApi.ReportCountryType().then(res => { ReportCountryTypeOptions.value = Object.values(res.data.reporter || {}); });
  QueryDataApi.PartnerCountriesType().then(res => { PartnerCountriesTypeOptions.value = Object.values(res.data.partner || {}); });
  QueryDataApi.getOtherType().then(res => { checkList.value = Object.values(res.data.dataCol || {}); });
 
});
</script>

<style lang="scss" scoped>
.demo-collapse {
  max-width: 1200px; // 适当增加最大宽度
  margin: 0 auto;

  :deep(.el-collapse) {
    border: 1px solid #ebeef5;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    background: #fff;
  }

  :deep(.el-collapse-item__header) {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    padding: 0 24px;
    height: 56px;
    transition: all 0.3s;
  }

  :deep(.el-collapse-item__header):hover,
  :deep(.el-collapse-item__header).is-active {
    color: #409eff;
    background-color: #f5f7fa;
  }

  :deep(.el-collapse-item__content) {
    padding: 24px;
    font-size: 14px;
    color: #606266;
    background: #fafafa;
  }

  .search-form {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));

    align-items: start;

    :deep(.el-form-item) {
      margin-bottom: 18px;
    }

    :deep(.el-form-item__label) {
      font-weight: 500;
      color: #606266;
    }
  }

  .date-type-group {
    display: flex;
    align-items: center;
    margin-bottom: 12px;

    .el-radio-group {
      display: flex;
      gap: 16px;
    }
  }

  .date-pickers {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 12px;

    :deep(.el-date-editor) {
      width: 100%;
      width: 270px;
    }
  }

  .form-actions {
    display: flex;
    justify-content: space-between;

    margin-top: 20px;
    padding-top: 16px;
    border-top: 1px solid #eee;

    .el-button {
      min-width: 80px;
    }
  }

  .active-item :deep(.el-collapse-item__content) {
    background-color: #f8f9fe;
    transition: background-color 0.3s;
  }

  // 移动端适配
  @media (max-width: 768px) {
    padding: 12px;

    :deep(.el-collapse-item__header) {
      height: 48px;
      padding: 0 16px;
      font-size: 15px;
    }

    :deep(.el-collapse-item__content) {
      padding: 16px;
    }

    .search-form {
      grid-template-columns: 1fr;
      grid-gap: 16px;
    }

    .date-pickers {
      grid-template-columns: 1fr;

      :deep(.el-date-editor) {
        max-width: 100%;
      }
    }

    .form-actions {
      display: flex;

      .el-button {
        width: 100%;
        margin-left: 0;
      }
    }

    .hs-popover-content {
      width: 100% !important;
      max-width: 100vw;
      padding: 8px;
    }
  }

  @media (max-width: 480px) {
    :deep(.el-form-item) {
      flex-direction: column;
      align-items: flex-start !important;
    }

    :deep(.el-form-item__label) {
      margin-bottom: 8px;
    }

    :deep(.el-select),
    :deep(.el-input) {
      width: 100%;
    }
  }
}
.selected-hs-popover {
  max-height: 400px;
  overflow-y: auto;
  padding: 8px;

  .empty-tip {
    color: #999;
    text-align: center;
    padding: 10px;
  }

  .hs-list {
    .hs-item {
      padding: 6px 12px;
      margin: 4px 0;
      background: #f5f7fa;
      border-radius: 4px;
      font-size: 13px;

      &:hover {
        background: #ebedf0;
      }
    }
  }
}
</style>
